package cn.antcore.common.security.handler;

import cn.antcore.common.user.AuthUserDetails;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功处理器
 * <br>
 * Created by Hong 2024/5/28
**/
public class GoAuthenticationLoginSuccessHandler extends AbstractAuthenticationHandler implements AuthenticationSuccessHandler {

    private final RequestCache requestCache = new HttpSessionRequestCache();

    public GoAuthenticationLoginSuccessHandler(ObjectMapper objectMapper) {
        super(objectMapper);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 获取来源页-> 登录成功跳转回来源页
        SavedRequest savedRequest = this.requestCache.getRequest(request, response);
        AuthUserDetails details = (AuthUserDetails) authentication.getPrincipal();
        Map<String, Object> result = new HashMap<>();
        result.put("username", details.getUsername());
        result.put("token", request.getSession().getId());
        if (savedRequest != null) {
            result.put("redirectUrl", savedRequest.getRedirectUrl());
            this.requestCache.removeRequest(request, response);
        } else {
            result.put("redirectUrl", "/");
        }
        success(response, result);
    }
}
